/*
------------------------------------------------------------------------------------------------------
1.订单的提交者可能是TSR或者Supervisor,程序自动为提交者找到上一级审批者为ASM角色用户
   modeified by xiaojiang 2011-07-20

2. 自动触发退货订单审批流程 
    create by xiaojiang 2011-06-30
    
3.  退货订单工作流审批最终通过后，向对应经销商和CSR发送邮件和传真通知
     modified by xiaojiang 2011-07-20            
------------------------------------------------------------------------------------------------------
*/

trigger ReadForWorkflow on Order__c (after insert,after update) {

 if(trigger.Isinsert){
    final string keyRTO='经销商退订';
    final string keyRTO1='经销商订单';
    final string titleSupervisor='Sales Supervisor';
    final string titleTSR='Sales Rep';
    final string titleASM='Area/District Sales Manager';
    list<Order__c> lO=new list<Order__c>();
    
    for(Order__c o:lO){
        if(o.OrderType__c==keyRTO||o.OrderType__c==keyRTO){
            lO.add(o);
        }
    }
    
    if(lO.size()>0){
        id submitManager;
        //查询当前用户信息
        user curUser=[select id,Title__c,ManagerId from user where id=:userInfo.getUserId()][0];
        //如果提交人是supervisor
        if(curUser.Title__c==titleSupervisor){
            submitManager=curUser.ManagerId;
        }else{
            //如果提交人是TSR，需要找TSR上两级经理
            if(curUser.Title__c==titleTSR){
                list<user> luser=[select id,Title__c,ManagerId from user where id=:curUser.ManagerId];
                if(luser.size()>0){
                  curUser=luser[0];
                  if(curUser.Title__c==titleASM){
                      submitManager=curUser.id;
                  }else{
                      submitManager=curUser.ManagerId;
                  }
                    
                }
            }
        }
        
        //赋值第一级审批经理信息
        for(Order__c o:lO){
            o.ManageUser__c=submitManager;
            //销售订单或经销商订单名称格式：经销商所在区域+日期
            o.Name=o.DistributorRegionName__c+'-'+string.valueOf(date.today());
        }
        
        //更新
        update lO;
        
        //审批流调用
        for(Order__c o:lO){            
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();   
            req1.setObjectId(o.id);
            Approval.ProcessResult result = Approval.process(req1);             
        }        
    } 
 }else{
     //当审批流最后一级CSR审批通过时，触发更新trigger
     if(trigger.IsUpdate){
         List<String> toAddresses = new List<String>();
         List<String> ccAddresses = new List<String>();
         string strBody='';
         string strSubject='';
         
         for(Order__c o:trigger.new){
             if(trigger.oldMap.get(o.id).CSRApproval__c!=trigger.newMap.get(o.id).CSRApproval__c&&o.CSRApproval__c){
                 //邮件发送    
                 toAddresses=new list<string>();
                 toAddresses.add(o.DistributorEmail__c);
                 strSubject='您的退货订单流程已经审批完成';
                 strBody='您的退货订单:'+o.Name+'已经在'+date.today()+'审批完成。';
                 //调用ws发送邮件
                 EmailFunction.SendEmail(toAddresses, ccAddresses, strBody, strSubject);
                 
                 //传真发送给经销商
                String xml = '<?xml version="1.0" encoding="UTF-8"?>';
                xml += '<SendFaxReq>';
                xml += '<Head>';
                xml += '<UserInfo>';
                ExternalWebServiceConfiguration__c ex=ExternalWebServiceConfiguration__c.getValues('HiFax');
                xml += '<UserName>'+ex.UserName_del__c+'</UserName>';
                xml += '<Password>'+ex.Password__c+'</Password>';
                xml += '<Accresskey>'+ex.AccessKey__c+'</Accresskey>';
                xml += '</UserInfo>';
                xml += '</Head>';
                xml += '<Body>';
                xml += '<SendFileList>';
        
                xml += '<SendFile>';
                xml += '<FileName>Fax.html</FileName>';
                
                String html ='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
                html+='<html xmlns="http://www.w3.org/1999/xhtml">';
                html+='<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>退货订单已经完成</title></head>';
                html+='<body>';
                html+='<div style="text-align:center;">尊敬的'+o.DistributorContact__c+'。您的退货订单：'+o.Name+'于'+date.today()+'已经审批完成。</div>';
                html+='</body>';
                 html+='</html>';
                String fileEncoding =EncodingUtil.base64Encode(Blob.valueOf(html));
                
                xml += '<FileEncoding>' + fileEncoding + '</FileEncoding>';
                xml += '</SendFile>';
                
                xml += '</SendFileList>';
                xml += '<RecipientList>';
                xml += '<Recipient>';
                xml += '<ClientName>'+o.id+'</ClientName>';
                xml += '<Company></Company>';
                xml += '<FaxNumber>'+o.DistributorFax__c+'</FaxNumber>';
                xml += '</Recipient>';
                xml += '</RecipientList>';
                xml += '</Body>';
                xml += '</SendFaxReq>';
                
                HiFaxCallOut.FaxServiceSoap c = new HiFaxCallOut.FaxServiceSoap();
                c.SendFax(xml);                                                  
             }
         } 
     }
 }    

}